package marco.android.CouchControl;

import java.util.HashMap;
import marco.android.CouchControl.R;

import android.content.Context;
import android.media.AudioManager;
import android.media.SoundPool;

public class AudioHelper
{
	private static AudioHelper mInstance = null;
	private SoundPool mSoundPool;
	private HashMap<Integer, Integer> mSoundPoolMap;
	private AudioManager  mAudioManager;
	private Context mContext;
 
	/**
	 * Hidden default constructor.
	 */
	private AudioHelper()
	{
	}
	 
	/**
	 * Initializes the storage for the sounds
	 *
	 * @param theContext The Application context
	 */
	private AudioHelper(Context theContext)
	{
		 mContext = theContext;
	     mSoundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 0);
	     mSoundPoolMap = new HashMap<Integer, Integer>();
	     mAudioManager = (AudioManager)mContext.getSystemService(Context.AUDIO_SERVICE);
	} 
  
	/**
	 * Requests the instance of the Sound Manager and creates it
	 * if it does not exist.
	 *
	 * @return Returns the single instance of the SoundManager
	 */
	static synchronized public AudioHelper getInstance(Context c)
	{
	    if (mInstance == null)
	      mInstance = new AudioHelper(c);
	    return mInstance;
	 }

	/**
	 * Add a new Sound to the SoundPool
	 *
	 * @param Index - The Sound Index for Retrieval
	 * @param SoundID - The Android resource ID for the Sound asset.
	 */
	public void addSound(int Index, int SoundID)
	{
		mSoundPoolMap.put(Index, mSoundPool.load(mContext, SoundID, 1));
	}
 
//	/**
//	 * Loads the various sound assets
//	 * Currently hardcoded but could easily be changed to be flexible.
//	 */
//	public static void loadSounds()
//	{
//		mSoundPoolMap.put(1, mSoundPool.load(mContext, R.raw.starwars, 1));
//		mSoundPoolMap.put(2, mSoundPool.load(mContext, R.raw.terminator, 1));
//	}
 
	/**
	 * Plays a Sound
	 *
	 * @param index - The Index of the Sound to be played
	 * @param speed - The Speed to play, not currently used but included for compatibility
	 */
	public void playSound(int index, float speed)
	{
		float streamVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
		streamVolume = streamVolume / mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
		mSoundPool.play(mSoundPoolMap.get(index), streamVolume, streamVolume, 1, 0, speed);
	}
 
	/**
	 * Stop a Sound
	 * @param index - index of the sound to be stopped
	 */
	public void stopSound(int index)
	{
		mSoundPool.stop(mSoundPoolMap.get(index));
	}
 
	/**
	 * Deallocates the resources and Instance of SoundManager
	 */
	public void Shutdown()
	{
		mSoundPool.release();
		mSoundPool = null;
	    mSoundPoolMap.clear();
	    mAudioManager.unloadSoundEffects();
	    mInstance = null;
 
	}
}